<template>
    <div>
        <!-- 面包屑导航区域 -->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>商品分类</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片区域 -->
        <el-card>
            <!-- 警告框 -->
            <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" :closable="false" show-icon></el-alert>
            <!-- 选择商品分类区 -->
            <el-row class="cat_opt">
                <el-col>
                    <!-- 商品分类级联选择框 -->
                    <span>选择商品的分类：
                        <el-cascader expand-trigger="hover" :options="catelist" :props="cateProps"
                            v-model="selectedCateKeys" @change="handleChange">
                        </el-cascader>
                    </span>
                    <!-- tab页签区 -->
                    <el-tabs v-model="activeName" @tab-click="handleTabClick">
                        <!-- 动态参数tab -->
                        <el-tab-pane label="动态参数" name="many">
                            <el-button type="primary" :disabled="isBtnaDisable" @click="addDialogVisible=true">添加动态参数
                            </el-button>
                            <!-- 动态参数表格 -->
                            <el-table :data="manyTableData">
                                <!-- 下拉列 -->
                                <el-table-column type="expand">
                                    <template slot-scope="scope">
                                        <!-- 循环渲染tag标签 -->
                                        <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable
                                            @close="handleClose(i,scope.row)">{{item}}
                                        </el-tag>
                                        <!-- 添加新标签文本框和按钮 -->
                                        <el-input class="input-new-tag" v-if="scope.row.inputVisible"
                                            v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                                            @keyup.enter.native="handleInputConfirm(scope.row)"
                                            @blur="handleInputConfirm(scope.row)">
                                        </el-input>
                                        <el-button v-else class="button-new-tag" size="small"
                                            @click="showInput(scope.row)">+ New
                                            Tag</el-button>
                                    </template>
                                </el-table-column>
                                <!-- 索引列 -->
                                <el-table-column type="index"></el-table-column>
                                <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                                <!-- 操作按钮列 -->
                                <el-table-column label="操作">
                                    <template slot-scope="scope">
                                        <el-button type="primary" icon="el-icon-edit" size="mini"
                                            @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                                        <el-button type="danger" icon="el-icon-delete" size="mini"
                                            @click="removeParams(scope.row.attr_id)">删除</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </el-tab-pane>
                        <!-- 静态参数tab -->
                        <el-tab-pane label="静态参数" name="only">
                            <el-button type="primary" :disabled="isBtnaDisable" @click="addDialogVisible=true">添加静态参数
                            </el-button>
                            <!-- 静态参数表格 -->
                            <el-table :data="onlyTableData">
                                <!-- 下拉列 -->
                                <el-table-column type="expand">
                                    <template slot-scope="scope">
                                        <!-- 循环渲染tag标签 -->
                                        <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable
                                            @close="handleClose(i,scope.row)">{{item}}
                                        </el-tag>
                                        <!-- 添加新标签文本框和按钮 -->
                                        <el-input class="input-new-tag" v-if="scope.row.inputVisible"
                                            v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                                            @keyup.enter.native="handleInputConfirm(scope.row)"
                                            @blur="handleInputConfirm(scope.row)">
                                        </el-input>
                                        <el-button v-else class="button-new-tag" size="small"
                                            @click="showInput(scope.row)">+ New
                                            Tag</el-button>
                                    </template>
                                </el-table-column>
                                <!-- 索引列 -->
                                <el-table-column type="index"></el-table-column>
                                <el-table-column label="属性名称" prop="attr_name"></el-table-column>
                                <!-- 操作按钮列 -->
                                <el-table-column label="操作">
                                    <template slot-scope="scope">
                                        <el-button type="primary" icon="el-icon-edit" size="mini"
                                            @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                                        <el-button type="danger" icon="el-icon-delete" size="mini"
                                            @click="removeParams(scope.row.attr_id)">删除</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </el-tab-pane>
                    </el-tabs>
                </el-col>
            </el-row>
        </el-card>
        <!-- 添加参数对话框 -->
        <el-dialog :title="'添加'+this.titleText" :visible.sync="addDialogVisible" width="50%" @close="addDialogClose">
            <!-- 添加对话框表单区 -->
            <el-form :model="addForm" :rules="addFormrules" ref="addFormRef" label-width="100px">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="addForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addParams">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 修改参数对话框 -->
        <el-dialog :title="'修改'+this.titleText" :visible.sync="editDialogVisible" width="50%" @close="editDialogClose">
            <!-- 添加对话框表单区 -->
            <el-form :model="editForm" :rules="addFormrules" ref="editFormRef" label-width="100px">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="editForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editParams">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
    export default {
        data() {
            return {
                //商品分类数据
                catelist: [],
                //级联选择框的配置对象
                cateProps: {
                    value: 'cat_id',
                    label: 'cat_name',
                    children: 'children'
                },
                //保存级联选择框选择的分类对应的id
                selectedCateKeys: [],
                //被激活的页签名称，会保存tab-pane的name属性
                activeName: 'many',
                //动态参数数据
                manyTableData: [],
                //静态参数数据
                onlyTableData: [],
                //控制添加参数对话框显示的布尔值
                addDialogVisible: false,
                //添加参数表单对象
                addForm: {
                    attr_name: ''
                },
                //添加参数表单验证规则
                addFormrules: {
                    attr_name: [
                        { required: true, message: '请输入参数名称', trigger: 'blur' },
                    ]
                },
                //控制编辑分类参数对话框的显示布尔值
                editDialogVisible: false,
                //编辑表单数据对象
                editForm: {
                },
                //
            }
        },

        created() {
            this.getCateList()
        },

        methods: {
            //获取所有商品分类数据
            async getCateList() {
                const { data: res } = await this.$http.get('categories')
                if (res.meta.status !== 200) {
                    return this.$message.error('获取商品列表失败')
                }
                this.catelist = res.data
            },
            //级联选择框选中项变化的时候触发的函数
            async handleChange() {
                this.getParamsData()
                if (this.selectedCateKeys.length !== 3) {
                    this.selectedCateKeys = []
                    this.manyTableData = []
                    this.onlyTableData = []
                }
            },
            //tab页签被点击触发事件
            async handleTabClick() {
                this.getParamsData()
            },
            //获取商品分类参数的方法
            async getParamsData() {
                //设置级联选择框只能选择第三级分类，通过判断保存id数组的长度实现，长度=3就说明选择的是第三级分类
                if (this.selectedCateKeys.length !== 3) {
                    //数组长度不为3就把双向绑定的
                    this.selectedCateKeys = []
                    return
                }
                //获得当前选择的面板和分类id发起获得参数表的数据的请求
                const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`,
                    { params: { sel: this.activeName } })
                if (res.meta.status !== 200) {
                    return this.$message.error('获取参数失败')
                }
                //赋值之前把返回的tag字符串循环成数组
                res.data.forEach(item => {
                    item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
                    //控制添加标签按钮和文本框显示的布尔值
                    item.inputVisible = false
                    //控制添加标签双向绑定的文本
                    item.inputValue = ''

                })
                console.log(res.data)
                //判断数据是动态参数还静态参数，进行分别保存
                if (this.activeName === 'many') {
                    this.manyTableData = res.data
                } else {
                    this.onlyTableData = res.data
                }
            },
            //监听添加参数对话框关闭事件触发函数
            addDialogClose() {
                this.$refs.addFormRef.resetFields()
            },
            //对添加参数表单进行验证，然后发起添加参数请求
            addParams() {
                this.$refs.addFormRef.validate(async valid => {
                    if (!valid) return
                    const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`,
                        { attr_name: this.addForm.attr_name, attr_sel: this.activeName })
                    if (res.meta.status !== 201) {
                        return this.$message.error('添加参数失败')
                    }
                    this.$message.success('添加参数成功')
                    this.getParamsData()
                    this.addDialogVisible = false
                })
            },
            //显示编辑分类参数的函数
            async showEditDialog(id) {
                const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/` + id,
                    { params: { attr_sel: this.activeName } })
                if (res.meta.status !== 200) {
                    return this.$message.error('获取参数信息失败')
                }
                this.editForm = res.data
                this.editDialogVisible = true
            },
            //监听修改参数对话框关闭事件触发函数
            editDialogClose() {
                this.$refs.editFormRef.resetFields()
            },
            //点击按钮修改参数信息
            editParams() {
                this.$refs.editFormRef.validate(async valid => {
                    if (!valid) return
                    const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
                        { attr_name: this.editForm.attr_name, attr_sel: this.activeName })
                    if (res.meta.status !== 200) {
                        return this.$message.error('修改参数信息失败')
                    }
                    this.$message.success('修改参数信息成功')
                    this.getParamsData()
                })
                this.editDialogVisible = false
            },
            //根据id删除参数点击事件
            async removeParams(id) {
                const confirmResult = await this.$confirm('该操作会删除此分类参数, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(error => error)
                if (confirmResult !== 'confirm') {
                    return this.$message.info('已取消删除')
                }
                const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/` + id)
                if (res.meta.status !== 200) {
                    return this.$message.error('删除参数失败')
                }
                this.$message.success('删除参数成功')
                this.getParamsData()
            },
            //添加分类标签的点击显示文本框输出
            showInput(row) {
                row.inputVisible = true
                //让文本框自动获得焦点
                this.$nextTick(_ => {
                    this.$refs.saveTagInput.$refs.input.focus();
                })
            },
            //文本框失去焦点或按下回车
            handleInputConfirm(row) {
                // 如果输入空格或者没输入东西
                if (row.inputValue.trim().length === 0) {
                    row.inputValue = ''
                    row.inputVisible = false
                    return
                }
                //在前段吧字符串渲染出来
                row.attr_vals.push(row.inputValue)
                //清空字符串
                row.inputValue = ''
                this.saveAttrVals(row)
            },
            //向服务器保存修改的tag分类标签
            async saveAttrVals(row) {
                // 发起请求添加分类标签
                const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
                    attr_name: row.attr_name,
                    attr_sel: row.attr_sel,
                    attr_vals: row.attr_vals.join(' ')
                })
                if (res.meta.status !== 200) {
                    return this.$message.error('修改参数失败')
                }
                this.$message.success('修改参数成功')
                //切换输入框为按钮
                row.inputVisible = false
            },
            //tag标签点击叉号事件
            handleClose(i, row) {
                row.attr_vals.splice(i, 1)
                this.saveAttrVals(row)
            }
        },//方法最外层
        //计算属性
        computed: {
            //判断按钮是否可以被点击的函数
            isBtnaDisable() {
                if (this.selectedCateKeys.length !== 3) {
                    return true
                }
                return false
            },
            //获取分类的id
            cateId() {
                if (this.selectedCateKeys.length === 3) {
                    return this.selectedCateKeys[2]
                }
                return null
            },
            //动态计算添加参数对话框标题文本
            titleText() {
                if (this.activeName === 'many') {
                    return '动态参数'
                }
                return '静态属性'
            },
            //
        }
    }
</script>
<style scoped>
    .cat_opt {
        margin: 15px;
    }

    .el-cascader {
        width: 30%;
    }

    .input-new-tag {
        width: 150px;
    }
</style>